const express = require("express");
const request = require('request');
const axios = require('axios');
let access_token = ''
async function speechSynthesis(data) {
    const token = await getAKAndSK()
    console.log(data.body)
    const taskId = await createWork(token, data.body.text, data.body.voice);
    if (taskId) {
        const taskIds = []
        taskIds.push(taskId)
        const res = await getWorkByTaskId(taskIds, token)
        return {
            code: 200,
            msg: '请求成功',
            data: res.data.tasks_info
        }
    }else {
        return {
            code: 200,
            msg: '创建失败',
            data: null
        }
    }
}

async function getWorkByTaskIdHttp(data) {
    const taskIds = data.query.taskIds
    const token = await getAKAndSK()
    const res = await getWorkByTaskId(taskIds, token)
    return {
        code: 200,
        msg: '请求成功',
        data: res.data.tasks_info
    }
}

async function createWork(token, text, voice) {
    const res = await axios.post(`https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=${token}`, JSON.stringify({
        text:text,
        format: "mp3-16k",
        voice: voice,
        lang:"zh",
        speed: 5,
        break: 1000
    }),{
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
    });
    if (res.data.error_code) {
        return null
    }else {
        return res.data.task_id
    }
}

async function getWorkByTaskId(taskIds, token) {
    return await axios.post(`https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=${token}`, JSON.stringify({
        task_ids: taskIds
    }), {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
    })
}

async function getAKAndSK() {
    const client_id = 'lhvzj9Mr1AMywK2SOkZJRTJL'
    const client_secret = 'fp27MY4B9wUvVh1NJo9fDFZVUR0oDlSA'
    const grant_type = 'client_credentials'
    const res = await axios.post(`https://aip.baidubce.com/oauth/2.0/token?client_id=${client_id}&client_secret=${client_secret}&grant_type=${grant_type}`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
    });
    if (res?.data?.access_token) {
        access_token = res.data.access_token
        return res.data.access_token
    }else {
        return  null
    }
}


exports.speechSynthesis = speechSynthesis
exports.getWorkByTaskIdHttp = getWorkByTaskIdHttp
